package cn.edu.zafu.bigdata.Wym;

import java.io.*;
import java.net.*;

public class Wym_TCPChatClient {
    private Socket clientSocket;
    private PrintWriter out;
    private BufferedReader in;

    // 构造方法，初始化客户端Socket并连接到服务端
    public Wym_TCPChatClient(String hostname, int port) throws IOException {
        clientSocket = new Socket(hostname, port);
        out = new PrintWriter(clientSocket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    }

    // 启动客户端，分别启动发送消息和接收消息的线程
    public void start() {
        new Thread(this::readMessage).start();
        new Thread(this::sendMessage).start();
    }

    // 发送消息的方法
    private void sendMessage() {
        try {
            BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
            String inputLine;
            System.out.println("客户端请输入：");
            // 循环读取客户端用户的输入
            while ((inputLine = stdin.readLine()) != null) {
                // 发送消息到服务端
                out.println("客户端：" + inputLine);
                System.out.println("客户端请输入：");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 接收消息的方法
    private void readMessage() {
        try {
            String serverMessage;
            // 循环读取服务端发送的消息
            while ((serverMessage = in.readLine()) != null) {
                // 打印接收到的服务端消息
                System.out.println(serverMessage);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 主方法，启动客户端
    public static void main(String[] args) throws IOException {
        String hostname = "127.0.0.1";
        int port = 12345;
        Wym_TCPChatClient client = new Wym_TCPChatClient(hostname, port);
        client.start();
    }
}



